package com.example.up.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import com.example.mcu.serial.SerialSend;
import com.example.up.Boot;
import com.example.up.MainActivity;
import com.example.up.R;
import com.example.up.util.Content;
import com.example.up.util.HttpUtil;

import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ConfirmDialog extends Dialog {

	private Timer time = new Timer();
	private Context context;
	private TextView titleTv, contentTv;
	private View okBtn, cancelBtn;
	private OnDialogClickListener dialogClickListener;
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	private String urls = null;
	private downloadApkThread thread = null;
	private static boolean isTrue = false;
	static File mcufile = null;
	private boolean cancelUpdate = false;
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;

	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;

	public ConfirmDialog(Context context, int theme, String url1) {
		super(context, theme);
		this.context = context;
		urls = url1;
		initalize();
		// TODO Auto-generated constructor stub
	}

	/*
	 * public ConfirmDialog(Context context,HashMap<String, String> map) {
	 * super(context); this.context = context; mHashMap=map; initalize(); }
	 */

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置

				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// Toast.makeText(MainActivity.this, "下载完成",
				// Toast.LENGTH_LONG).show();
				if (isTrue) {
					thread.interrupt();
					thread = null;
					isTrue = false;
				}
			
				Intent intent = new Intent(context, Boot.class);
				intent.putExtra("path", mcufile.getAbsolutePath());
				context.startActivity(intent);
				SerialSend.getInstance().sendStatus(
						SerialSend.Serial_BOOTLOADER);
				 Content.sendStartBoradcast(context,"mcu_update_end");
				TimerTask task = new TimerTask() {

					@Override
					public void run() {
						Content.killMoco(context);
						SerialSend.getInstance().close();
					}
				};
				time.schedule(task, 1000);
				break;
			default:
				break;
			}
		};
	};

	private void initalize() {
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.confirm_dialog, null);
		setContentView(view);
		initWindow();

		titleTv = (TextView) findViewById(R.id.title_name);
		contentTv = (TextView) findViewById(R.id.text_view);
		okBtn = findViewById(R.id.btn_ok);
		cancelBtn = findViewById(R.id.btn_cancel);
		okBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
				showDownloadDialog();
			
				if (dialogClickListener != null) {
					dialogClickListener.onOKClick();
				}
			}
		});
		cancelBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
				HttpUtil.start(context);
				if (dialogClickListener != null) {
					dialogClickListener.onCancelClick();
				}
			}
		});
	}

	private void initWindow() {
		Window dialogWindow = getWindow();
		dialogWindow.setBackgroundDrawable(new ColorDrawable(0));
		dialogWindow
				.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
						| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		DisplayMetrics d = context.getResources().getDisplayMetrics();
		lp.width = (int) (d.widthPixels * 1);
		lp.y = 90;
		lp.height = 320;
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
	}

	public void setOnDialogClickListener(OnDialogClickListener clickListener) {
		dialogClickListener = clickListener;
	}

	public interface OnDialogClickListener {
		void onOKClick();

		void onCancelClick();
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 * @date 2012-4-26
	 * @blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// 获得存储卡的路径
					String sdpath = Environment.getExternalStorageDirectory()
							+ "/";
					mSavePath = sdpath + "download";

					URL url = new URL(urls);
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					mcufile = new File(mSavePath, urls.substring(urls
							.lastIndexOf("/") + 1));
					FileOutputStream fos = new FileOutputStream(mcufile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置

						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0) {
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
						try {
							sleep(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog() {
		
		final LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.mcu_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);

		Button cancel = (Button) v.findViewById(R.id.cancel);

		mDownloadDialog = new Dialog(context, R.style.Dialog_Fullscreen);
		@SuppressWarnings("deprecation")
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		mDownloadDialog.addContentView(v, params);

		Window dialogWindow = mDownloadDialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		dialogWindow.setGravity(Gravity.CENTER | Gravity.BOTTOM);
		// 显示的坐标
		lp.x = 0;
		lp.y = 1;
		lp.width = 320;

		dialogWindow.setAttributes(lp);

		mDownloadDialog.show();
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDownloadDialog.dismiss();
				// deleteFile(new File("/cache/update.zip"));
				// new FileService(mContext).delete(url);
				// HttpUtil.start(mContext);
				cancelUpdate = true;
			}
		});

		if (thread == null) {

			thread = new downloadApkThread();
			isTrue = true;
			thread.start();
		}
	}

}
